package com.cm.kits;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.List;


/**
 * win 进程工具包
 *
 * @author cm
 */
public class ProcessKits {

    /**
     * 判断指定进程是否存在
     *
     * @param processName
     * @return
     */
    public static Boolean isProcessExist(String processName) {
        try {
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                return isWindowsProcessExist(processName);
            }
            if (os.toLowerCase().startsWith("lin")) {
                return isLunuxProcessExist(processName);
            } else {
                return false;
            }

        } catch (Exception e) {
            return false;
        }
    }


    public static boolean isLunuxProcessExist(String processName) {

        BufferedReader bufferedReader = null;
        try {
            Process proc = Runtime.getRuntime().exec("ps -e");
            bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                // 判断是否存在
                if (line.contains(processName)) {
                    return true;
                }
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception ex) {
                }
            }
        }
    }

    public static boolean isWindowsProcessExist(String processName) {

        BufferedReader bufferedReader = null;
        try {
            String cmd = MessageFormat.format("{0}\\system32\\tasklist.exe", System.getenv("windir"));
            Process proc = Runtime.getRuntime().exec(cmd);
            bufferedReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
                // 判断是否存在
                if (line.contains(processName)) {
                    return true;
                }
            }
            return false;
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (Exception ex) {
                }
            }
        }
    }

    public static Boolean startProcess(List<String> exeFileFullPathNameList) {
        try {
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                startWindowsProcess(exeFileFullPathNameList);
            }
            if (os.toLowerCase().startsWith("lin")) {
                startLinuxProcess(exeFileFullPathNameList);
            } else {
                return false;
            }

            return true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }
    }

    private static void startWindowsProcess(List<String> exeFileFullPathNameList) {
        try {
            Runtime runtime = Runtime.getRuntime();
            for (String string : exeFileFullPathNameList) {
                runtime.exec(string);
            }
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

    private static void startLinuxProcess(List<String> exeFileFullPathNameList) {
        try {
            // 如果是 linux系统
            for (String processName : exeFileFullPathNameList) {
                // String commandString = MessageFormat.format("ps -ef | grep {0} | grep -v grep | awk '''{'print $2'}''' | xargs kill -9", processName);
                System.out.println(processName);
                // 当需要执行的linux命令带有管道符时（例如：ps -ef|grep java），用上面的方法是不行的，解决方式是将需要执行的命令作为参数传给shell
                String[] cmds = {"/bin/sh", "-c", processName};
                Runtime.getRuntime().exec(cmds);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    /**
     * 根据进程名称集合结束进程
     *
     * @param processNameList 进程名称集合 例如firefox,chrome 不带后缀
     * @return
     */
    public static Boolean killProcess(List<String> processNameList) {
        try {
            String os = System.getProperty("os.name");
            if (os.toLowerCase().startsWith("win")) {
                killWindowsProcess(processNameList);
            }
            if (os.toLowerCase().startsWith("lin")) {
                killLinuxProcess(processNameList);
            } else {
                return false;
            }

            return true;
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 在windows环境下根据进程名称结束进程
     *
     * @param processNameList 进程名称集合
     */
    private static void killWindowsProcess(List<String> processNameList) {
        try {
            // 如果是 windows系统
            for (String processName : processNameList) {
                // String commandString=MessageFormat.format("taskkill /f /IM phantomjs.exe", arg1)
                String commandString = MessageFormat.format("taskkill /f /IM {0}.exe", processName);
                Runtime.getRuntime().exec(commandString);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

    }

    /**
     * 在Linux环境下根据进程名称结束进程
     *
     * @param processNameList 进程名称集合
     */
    private static void killLinuxProcess(List<String> processNameList) {
        try {
            // 如果是 linux系统
            for (String processName : processNameList) {

                String commandString = MessageFormat.format("ps -ef | grep {0} | grep -v grep | awk '''{'print $2'}''' | xargs kill -9", processName);
                System.out.println(commandString);
                // 当需要执行的linux命令带有管道符时（例如：ps -ef|grep java），用上面的方法是不行的，解决方式是将需要执行的命令作为参数传给shell
                String[] cmds = {"/bin/sh", "-c", commandString};
                Runtime.getRuntime().exec(cmds);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }
}

